#THIS FILE IS AUTO GENERATED FROM THE TEMPLATE! DO NOT CHANGE!
set(CMAKE_SYSTEM_NAME Generic)
set(CMAKE_SYSTEM_VERSION 1)
cmake_minimum_required(VERSION 3.23)

# specify cross-compilers and tools
set(CMAKE_C_COMPILER riscv-none-elf-gcc)
set(CMAKE_CXX_COMPILER riscv-none-elf-g++)
set(CMAKE_ASM_COMPILER riscv-none-elf-gcc)
set(CMAKE_AR riscv-none-elf-ar)
set(CMAKE_OBJCOPY riscv-none-elf-objcopy)
set(CMAKE_OBJDUMP riscv-none-elf-objdump)
set(SIZE riscv-none-elf-size)
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)

# project settings
project(WCH_CH32V20X C CXX ASM)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_C_STANDARD 11)

# Target Processor{-march=rv32imac_zba_zbb_zbc_zbs_xw, }
add_compile_options(-march=rv32imacxw -mabi=ilp32 -msmall-data-limit=8 -msave-restore )
# Optimization
add_compile_options(-Os -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fno-common)
# Warnings
add_compile_options(-Wunused -Wuninitialized)
#Debugging
add_compile_options(-std=gnu99)

if ("${CMAKE_BUILD_TYPE}" STREQUAL "Release")
    message(STATUS "Maximum optimization for speed")
    add_compile_options(-Ofast)
elseif ("${CMAKE_BUILD_TYPE}" STREQUAL "RelWithDebInfo")
    message(STATUS "Maximum optimization for speed, debug info included")
    add_compile_options(-Ofast -g)
elseif ("${CMAKE_BUILD_TYPE}" STREQUAL "MinSizeRel")
    message(STATUS "Maximum optimization for size")
    add_compile_options(-Os)
else ()
    message(STATUS "Minimal optimization, debug info included")
    add_compile_options(-Og -g)
endif ()

include_directories(
        Core/Inc
        Peripheral/Inc
)

add_definitions(-DUSE_FULL_ASSERT)

file(GLOB_RECURSE SOURCES "Core/*.*" "Peripheral/*.*")
# 排除 ARM GCC 的启动文件
file(GLOB_RECURSE EXCLUDE_SRCS "Core/Startup/startup_ch32v20x_D8.S" "Core/Startup/startup_ch32v20x_D8W.S")
list(REMOVE_ITEM SOURCES ${EXCLUDE_SRCS})   # 从源文件列表(SOURCES)中剔除干扰文件(EXCLUDE_SRCS)

set(LINKER_SCRIPT ${CMAKE_SOURCE_DIR}/CH32V203C8T6.ld)

add_link_options(-T "${LINKER_SCRIPT}")
add_link_options(-nostartfiles -Xlinker --gc-sections -Wl,-Map,${PROJECT_NAME}.map  --specs=nano.specs --specs=nosys.specs )

add_executable(${PROJECT_NAME}.elf ${SOURCES} ${LINKER_SCRIPT})

set(HEX_FILE ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.hex)
set(BIN_FILE ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.bin)

add_custom_command(TARGET ${PROJECT_NAME}.elf POST_BUILD
        COMMAND ${CMAKE_OBJCOPY} -Oihex $<TARGET_FILE:${PROJECT_NAME}.elf> ${HEX_FILE}
        COMMAND ${CMAKE_OBJCOPY} -Obinary $<TARGET_FILE:${PROJECT_NAME}.elf> ${BIN_FILE}
        COMMENT "Building ${HEX_FILE}
Building ${BIN_FILE}")
